import React from 'react';
import { withRouter } from 'react-router-dom';
import { inject, observer} from 'mobx-react';
import { toJS } from 'mobx';
import { Icon, List, Tools,InputItem,DatePickerView,Button,Switch,Toast,Bubble } from 'weaver-mobile';
import { SelectPage } from 'weaver-mobile-page';
import moment from 'moment';

const getLabel = Tools.getLabel;
const { FormItem } = List;

@inject('calendarStore')
@withRouter
@observer
export default class SchduleSync extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typeVisible1: false, // 1：OA同步手机 2：手机同步OA
      typeVisible2: false,
      timeVisible: false,
      date: moment().format('YYYY-MM-DD'),
      value: new Date(),
      flod1: true,
      flod2: true,
      checked1: false,
      checked2: false,
      allOrSelect1: true, // 全部/选择
      allOrSelect2: true,
      valueTypeArray1: [], // 同步日程类型
      valueTypeArray2: [], // 同步本地日历
      calendarList1: [],
      calendarList2: [],
      calendarListStr1: [],
      calendarListStr2: [],
      selectArr: [],
    }
  }

 

  componentWillMount() {
    const {getWorkPlanType,getMobileCalendars,getSyncSetting,setState,OAtoLocal} = this.props.calendarStore;
    getWorkPlanType('',this.initType);
    getMobileCalendars(setState, ()=>{
      OAtoLocal === 3 && getSyncSetting('get',this.initState,'','');
    });

    // this.initType();
    setTimeout(() => {
      this.initState();
      this.initType();
      setState({syncLoading: false});
    }, 1000);
  }

  componentDidMount() {
    // this.initState();
    // this.initType();
    window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(514165,"日程同步") })

    this.initStartEndTime();
  }


  initStartEndTime = () => {
    const {setState} = this.props.calendarStore;
    let value = new Date();
    let startTime = '';
    let endTime = '';
    startTime = value.getFullYear() + '-' + this.setNum(value.getMonth()+1) + '-' + this.setNum(value.getDate()) +' '+ '00:00:00';
    if((value.getMonth()+1)+6 > 12) {
      endTime = value.getFullYear()+1 +'-'+this.setNum(((value.getMonth()+1)+6)%12) + '-' + this.setNum(value.getDate()) + ' '+ '00:00:00'; 
    }else{
      endTime = value.getFullYear() + '-' + this.setNum(((value.getMonth()+1)+6)) + '-' + this.setNum(value.getDate()) + ' ' + '00:00:00';
    }
    setState({starttime: startTime,endtime: endTime});
  }

  initState = () => {
    // 初始化自动同步信息
      const {autoToserver,autoTomobile,} = this.props.calendarStore;
      parseInt(autoTomobile, 10) === 1 ? this.setState({checked1: true}) :  this.setState({checked1: false})
      parseInt(autoToserver, 10) === 1 ? this.setState({checked2: true}) :  this.setState({checked2: false})
  }
  initType = () => {
    // 初始化选类型和本地日历
      const {typeOptions,calendarOptions,toOAscheduleTypes,toMobilescheduleTypes,mobileCalendar,toServerCalendars,OAtoLocal} = this.props.calendarStore;
      let arr1 = [];
      let arr2 = [];
      let arr3 = [];
      let allOrSelect1 = true;
      let allOrSelect2 = true;
      let valueTypeArray1_arr = this.allOrOne(typeOptions,true);
      let valueTypeArray2_arr = this.allOrOne(calendarOptions,true);
      typeOptions.length>0 && arr1.push(typeOptions[0].showname)
      calendarOptions.length>0 && arr2.push(calendarOptions[0].showname)
      calendarOptions && calendarOptions.map(res => {
        arr3.push(res.showname);
        return '';
      });
      if (calendarOptions && toMobilescheduleTypes) { // 同步到本地--同步日程类型
        allOrSelect1 = typeOptions.length === toMobilescheduleTypes.length;
        if (!allOrSelect1) {
          valueTypeArray1_arr = this.setSelectedTypes(typeOptions, toMobilescheduleTypes, true);
        }
      }
      if (calendarOptions && toServerCalendars) { // 同步到oa--同步本地日历
        allOrSelect2 = calendarOptions.length === toServerCalendars.length;
        if (!allOrSelect2) {
          valueTypeArray2_arr = this.setSelectedTypes(calendarOptions, toServerCalendars, false);
        }
      }
      if (OAtoLocal === 3) {
        this.setState({valueTypeArray1: valueTypeArray1_arr, valueTypeArray2: valueTypeArray2_arr,
                        calendarList1: this.allOrOne(calendarOptions,false,false,mobileCalendar),
                        calendarList2: toOAscheduleTypes.length == 0 ? this.allOrOne(typeOptions,false,false,toOAscheduleTypes) : toOAscheduleTypes,
                        calendarListStr1: mobileCalendar.length>0?mobileCalendar:arr2,calendarListStr2: arr1,selectArr: toServerCalendars.length>0?toServerCalendars:arr3,
                        allOrSelect1: allOrSelect1, allOrSelect2: allOrSelect2,
                        typeVisible1: allOrSelect1,
                      });
      } else {
        this.setState({ 
          valueTypeArray1: this.allOrOne(typeOptions,true), valueTypeArray2: this.allOrOne(calendarOptions,true),
          calendarList1: this.allOrOne(calendarOptions,false),calendarList2: this.allOrOne(typeOptions,false),
          calendarListStr1: arr2,calendarListStr2: arr1,selectArr: arr3,
        })
      }
  }

  setSelectedTypes = (allType, selectedType, isKey) => {
    let arr = [];
    if ( isKey ) {
      if (allType && selectedType) {
        if (selectedType.length === 0) {
          arr.push(allType[0].key);
        }
        selectedType.length>0 && allType.length>0 && allType.map(res => {
          if (selectedType.indexOf(res.key) > -1) {
            arr.push(res.key);
          }
        });
      } 
    } else {
      if (allType && selectedType) {
        if (selectedType.length === 0) {
          arr.push(allType[0].key);
        }
        selectedType.length>0 && allType.length>0 && allType.map(res => {
          if (selectedType.indexOf(res.showname) > -1) {
            arr.push(res.key);
          }
        });
      } 
    }
    return arr;
  } 

  allOrOne = (options, allOrOne, showname, calendar) => {
    // options：数组， allOrOne： 全部/选择，showname: true:返回showname,'': 返回key值
    let arr = [];
    options = toJS(options);
    calendar = toJS(calendar);
    if (calendar) {
      if (calendar.length == 0) {
        arr.push(options[0].key);
      }
      calendar.length>0 && options.length>0 && options.map(res => {
        if (calendar.indexOf(res.showname) > -1) {
          arr.push(res.key);
        }
      });
      return arr;
    }
    if(showname){
      if(allOrOne) {
        // 全部
        options.length>0 && options.map(res => {
          arr.push(res.showname);
          return '';
        });
        return arr;
      }else{
        // 默认第一个
        options.length>0 && arr.push(options[0].showname);
        return arr;
      }
    }else{
      if(allOrOne) {
        // 全部
        options.length>0 && options.map(res => {
          arr.push(res.key);
          return '';
        });
        return arr;
      }else{
        // 默认第一个
        options.length>0 && arr.push(options[0].key);
        return arr;
      }

    }
  }

  onShowType = (visible, name, allOrSelect) => {
    // 日程类型全部/选择
    const { typeOptions,calendarOptions } = this.props.calendarStore;
    if(name === 1) {
      let key = visible ? this.allOrOne(typeOptions, false) : this.allOrOne(typeOptions, true);
      this.setState({typeVisible1: !visible,allOrSelect1: !allOrSelect,timeVisible: false,valueTypeArray1: key})
    }
    if(name === 2) {
      let key = visible ? this.allOrOne(calendarOptions, false) : this.allOrOne(calendarOptions, true);
      let arr = visible ? this.allOrOne(calendarOptions, false, true) : this.allOrOne(calendarOptions, true, true);
      let str = [];
      if(!visible){
        str.push(calendarOptions[0])
      }else{
        calendarOptions && calendarOptions.map(res => {
          str.push(res);
          return '';
        })
      }
      this.setState({typeVisible2: !visible,allOrSelect2: !allOrSelect,timeVisible: false,valueTypeArray2: key,selectArr: arr});
    }
    name === 'timeVisible' && this.setState({timeVisible: !visible})
  }

  setNum = (num) => {
    if(num > 9){
      return num;
    }else{
      return '0'+num;
    }
  }

  setValue = (value) => {
    const {setState} = this.props.calendarStore;
    let nowdate = new Date().getFullYear() + '-' + this.setNum(new Date().getMonth()+1) + '-' + this.setNum(new Date().getDate());
    let valuedate = value.getFullYear() + '-' + this.setNum(value.getMonth()+1) + '-' + this.setNum(value.getDate());
    let time = nowdate === valuedate ? value.getHours()+':'+this.setNum(value.getMinutes())+':'+this.setNum(value.getSeconds()) : '00:00:00';
    let selectDate = valuedate + ' '+ time;
    let startTime = selectDate;
    let endTime =  selectDate;
  
    this.setState({value: value});
    if(valuedate < nowdate) { // 选择时间小于当前日期，结束时间为当前日期向后推6个月， 否则结束时间为选择时间向后推6个月
      value = new Date();
    }
    if((value.getMonth()+1)+6 > 12) {
      endTime = value.getFullYear()+1 +'-'+this.setNum(((value.getMonth()+1)+6)%12) + '-' + this.setNum(value.getDate()) + ' '+ '23:59:59'; 
    }else{
      endTime = value.getFullYear() + '-' + this.setNum(((value.getMonth()+1)+6)) + '-' + this.setNum(value.getDate()) + ' ' + '23:59:59';
    }   

    setState({starttime: startTime,endtime: endTime})
  }

  changeDate = (dates) => {
    let date = dates === null ? new Date() : dates;
    return date.getFullYear() + getLabel(26577,'年') + (date.getMonth()+1) + getLabel(33452,'月') + date.getDate() + getLabel(390,'日');
  }

  submit = (OAtoLocal) => {
    const {synctoServer,synctoMobile,setState,typeOptions,getSyncSetting} = this.props.calendarStore;
    const {valueTypeArray1,
          calendarListStr1,
          calendarList2,selectArr,
          valueTypeArray2,
          allOrSelect1} = this.state;
    let valueArr = [];
    typeOptions && typeOptions.map(res => {
      valueArr.push(res.key);
      return '';
    });
    let arr1 = allOrSelect1 ? valueArr : valueTypeArray1; 
    // let calList1 = calendarListStr1.length>0 ? calendarListStr1 : (calendarOptions ? calendarOptions[0].showname :'');
    let calList1 = calendarListStr1.length>0 ? calendarListStr1 : '';

    const isRequired = (data) => {
      return data&&data.length === 0 || data === '';
    }

    if(OAtoLocal === 1) {
      if(isRequired(arr1) || isRequired(calList1)) {
        Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
      }else{
        synctoMobile(arr1, calList1, setState);
        Toast.loading(getLabel(391133,'同步中...'),3,() => {
          this.props.history.go(-1);
        });
      }
    }

    if(OAtoLocal === 2) {
      if(isRequired(selectArr) || isRequired(selectArr)) {
        Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
      }else{
        synctoServer(selectArr, calendarList2, setState);
        Toast.loading(getLabel(391133,'同步中...'),3,() => {
          this.props.history.go(-1);
        });
      }
    }

    if(OAtoLocal === 3) {
      if(isRequired(arr1) || isRequired(calendarList2) || isRequired(calList1)) {
        Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
      }else{
        getSyncSetting('set','',calendarList2,arr1,calList1, selectArr);
        setTimeout(()=>{
          this.props.history.go(-1);
        },1000)
      }
    }
    // (OAtoLocal === 1 || OAtoLocal === 2) && Toast.loading(getLabel(391133,'同步中...'),3,() => {
    //   this.props.history.go(-1);
    // });
    // OAtoLocal === 3 && setTimeout(()=>{
    //   this.props.history.go(-1);
    // },1000)

  }

  setLabel = (num) => {
    if(num === 1) return getLabel(391131,'本地同步日程到OA');
    if(num === 2) return getLabel(391130,'OA同步日程到本地');
  }

  getLocToOA = () => {
    let field = [];
    field.push(
      <div className='schdulesync-icon' key='schdulesync-icon1'>
        <Icon type='synchronization-to-oa' />
        <label>{this.setLabel(1)}</label>          
      </div>
    )
    field.push(
      this.getFields()
    )

    return field;
  }

  getOAToLoc = () => {
    let field = [];
    field.push(
      <div className='schdulesync-icon' key='schdulesync-icon2'>
            <Icon type='synchronization-to-local'/>
            <label>{this.setLabel(2)}</label>
      </div>
    )
    field.push(
      this.getFields()
    )
    return field;
  }

  foldClick = (index) => {
    // 折叠,显隐
    const {flod1,flod2} = this.state;
    index===0 && this.setState({flod1: !flod1})
    index===1 && this.setState({flod2: !flod2})
  }

  switchClick = (index,checked) => {
    // 自动同步开关是否开启
    const {setState} = this.props.calendarStore;
    const {checked1,checked2} = this.state;
    const u = navigator.userAgent;
    let t = checked ? 0 : 1;
    if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
      if(index===1) {
        if(!checked && checked2){
          this.setState({checked1: !checked,checked2: checked})
          setState({autoTomobile: t,autoToserver: 0})
        }else{
          this.setState({checked1: !checked});
          setState({autoTomobile: t})
        }
      }
      if(index===2) {
        if(checked1 && !checked){
          this.setState({checked1: checked,checked2: !checked})
          setState({autoToserver: t,autoTomobile: 0})
        }else{
          this.setState({checked2: !checked});
          setState({autoToserver: t})
        }
      }
    
    }else{
      if(index===1) {
        setState({autoTomobile: t})
        this.setState({checked1: !checked});
      }
      if(index===2) {
        setState({autoToserver: t})
        this.setState({checked2: !checked});
      }
    }
  }

  typeOnChange = (data,name) => {
    let key = [];
    let arr = [];
    data && data.map(res => {
      key.push(res.key);
      return '';
    })
    name === 1 && this.setState({valueTypeArray1: key});
    if(name === 2) {
      data && data.map(res => {
        arr.push(res.showname);
        return '';
      })
      this.setState({valueTypeArray2: key,selectArr: arr});
    }
  }

  setCalendarChange = (data,name) => {
    let showname = [];
    let key = [];
    data && data.map(res => {
      showname.push(res.showname);
      key.push(res.key);
      return '';
    })
    name === 1 && this.setState({calendarList1: key,calendarListStr1: showname});
    name === 2 && this.setState({calendarList2: key,calendarListStr2: showname});
  }

  getLocToOAset = () => {
    const {flod1,flod2} = this.state;
    let groups = [];
    Array.from(new Array(2)).map((i,index) => {
      groups.push(
        // 分组
        <div className='form-fold-group' key={index}>
          <div className='fold-title' onClick={() => {this.foldClick(index)}}>
            {this.setLabel(2-index)}
            <Icon className="flod-icon" type={(index===0 ? flod1:flod2 ) ? 'up' : 'down'} />
          </div>
          <div className={(index===0 ? flod1:flod2 ) ? 'show' : 'hide'}>
            {this.typeSelect(index+1)}
          </div>
        </div>
      )
      return '';
    })

    return groups;
  }

  isAndroid = (num) => {
    const u = navigator.userAgent;
    const Android =  u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    const { OAtoLocal } = this.props.calendarStore;
 
    if((OAtoLocal === 2 && Android) || (OAtoLocal === 3 && num === 2 && Android) ) {
      return true;
    }else{
      return false;
    }
  }

  isAndroid1 = (num) => {
    const u = navigator.userAgent;
    const Android =  u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    const { OAtoLocal } = this.props.calendarStore;
 
    if((OAtoLocal === 1 && Android) || (OAtoLocal === 3 && num === 1 && Android) ) {
      return true;
    }else{
      return false;
    }
  }

  typeSelect = (num) => {
    const {typeVisible1,typeVisible2,
          timeVisible,
          checked1,checked2,
          allOrSelect1,allOrSelect2,
          valueTypeArray1,valueTypeArray2,
          calendarList1,calendarList2,
        } = this.state;
    const {selectSysnc1,selectSysnc2,
            selectType1,selectType2,
            OAtoLocal,typeOptions,calendarOptions,
          } = this.props.calendarStore;
    const options = typeOptions;
    let typeNum = num ? num : OAtoLocal;
    let typeVisible = typeNum === 1 ? typeVisible1 : typeVisible2;
    let checked = typeNum === 1 ? checked1 : checked2;
    let allOrSelect = typeNum === 1 ? allOrSelect1 : allOrSelect2;
    let field = [];
    let fields = [];

    OAtoLocal === 3 && field.push(
      <FormItem 
        key={'switch'}
        label={getLabel(32221,'自动同步')}
        line
        content={(<Switch checked={checked} onClick={() => {this.switchClick(typeNum,checked)}}/>)}
      />,
    )
    !this.isAndroid (typeNum) && field.push(
      <FormItem 
        key={'endtimebefore'}
        label={typeNum === 1 ? getLabel(391134,'同步日程类型') : (typeNum === 2 ? getLabel(391135,'同步本地日历'): '')}
        wrap="nowrap"
        border    
        content={(<InputItem id="endtimebefore" editable={false} placeholder= {getLabel(19785,"结束前") }
                    onClick={(e) => {this.onShowType(allOrSelect, typeNum, allOrSelect)} } value={allOrSelect === true ? getLabel(332,'全部'):getLabel(33251,'选择')} />)}
        extra={[<Icon key="right" type="right"  />]}
      />,
    )
    !allOrSelect && field.push(
      <FormItem 
        key={'selecttype'}
        label={getLabel(391136,'选择类型')}
        wrap="nowrap"
        border    
        content={(
          <SelectPage
            key={'selecttype1'}
            options={typeNum === 1 ? options : calendarOptions}
            store={typeNum === 1 ? selectType1 : selectType2}
            valueArray={typeNum === 1 ? valueTypeArray1 : valueTypeArray2}
            multiChoose={true}
            onChange={(datas) => {this.typeOnChange(datas,typeNum)} }
            viewAttr={3}
            />
          )}
      />
    )
    !this.isAndroid1 (typeNum) && field.push(
      <FormItem 
        key={'savetolocaltion'}
        label={typeNum === 1 ? getLabel(391328,"保存到本地日历") : (typeNum === 2 ? getLabel(391329,"保存为日程类型") : '')}
        wrap="nowrap"
        border    
        content={(
          <SelectPage
            key={'savetolocaltion1'}
            options={typeNum === 1 ? calendarOptions : options}
            store={typeNum === 1 ? selectSysnc1 : selectSysnc2}
            valueArray={typeNum === 1 ? calendarList1 : calendarList2}
            multiChoose={false}
            onChange={(datas) => {this.setCalendarChange(datas,typeNum)} }
            viewAttr={3}
          />
        )}
      />
    );
    timeVisible && field.push(
      <div className='datepicker-mask' key='timePicker' onClick={() => {this.setState({timeVisible: false})}}>
        <List>
        <DatePickerView
          mode="date"
          minDate={new Date(moment().subtract(1, 'year').format("YYYY-MM-DD"))} // 当前时间向前推一年
          value={this.state.value}
          onChange={(e) => {this.setValue(e)}}
        />
        </List>
      </div>
    )
    fields.push(
      <div className='schdulesync-item' style={{height: '100%'}} key='schdulesync-item'>
        <List>
            {field}
        </List>
      </div>
    )
    return fields;
  }

  getFields = () => {
    const {timeVisible,value} = this.state;
    const {OAtoLocal} = this.props.calendarStore; 
    let field = [];
    if(OAtoLocal === 1 || OAtoLocal === 2) {
      field.push(
        <FormItem
          key={6}
          label={getLabel(391137,'同步以下日期开始的日程')}
          wrap="nowrap"
          border
          content={(
            <InputItem id="benginTime" editable={false} 
              onClick={(e) => {this.onShowType(timeVisible,'timeVisible')} } 
              value={this.changeDate(value)} />)}
              extra={[<Icon key="right" type="right"  />]}
            >
        </FormItem>,
      )
    }
    field.push(
      this.typeSelect()
    )
    return field;
  }

  getLoading = () => {
    return (
      <div className='loaidng-icon' key='loading'>
        <Icon type='loading' size='lg'/>
      </div>
    );
  }

  render() {
    const { OAtoLocal, syncLoading } = this.props.calendarStore;
    return(
      <div className='schdulesync-content'>
        {OAtoLocal === 1 && this.getOAToLoc()} 
        {OAtoLocal === 2 && this.getLocToOA()}
        {OAtoLocal === 3 && this.getLocToOAset()}
        {/* <div className='schdulesync-item' style={{height: '100%'}}>
          <List>
              {this.getFields()}
          </List>
        </div> */}
        <div className='schdulesync-button'>
          <Button type="primary" onClick={() => {this.submit(OAtoLocal)}}>{getLabel(386788,'确定')}</Button>
        </div>
        {syncLoading && this.getLoading()}
      </div>
    );
  }
}